package com.xd100.lzll.gm.util;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

public class JsonUtil {

	private static JsonConfig jc = new JsonConfig();
	@SuppressWarnings("rawtypes")
	private static Map<Class, String> excludes = new HashMap<Class, String>();

	private JsonUtil() {
	}

	@SuppressWarnings("rawtypes")
	public static String getExcludes(Class c) {
		if (excludes.containsKey(c))
			return excludes.get(c);
		boolean b = false;
		StringBuffer sb = new StringBuffer();
		for (Field f : c.getDeclaredFields()) {
			if (Collection.class.isAssignableFrom(f.getType())) {
				if (b)
					sb.append(",");
				sb.append(f.getName());
				b = true;
			}
		}
		String s = sb.toString();
		excludes.put(c, s);
		return s;
	}

	public static String from(Object o) {
		return JSONObject.fromObject(o).toString();
	}

	public static String from(Object[] o) {
		return JSONArray.fromObject(o).toString();
	}

	public static String from(Object o, String[] ex) {
		jc.setExcludes(ex);
		return JSONObject.fromObject(o, jc).toString();
	}

	public static String from(Object o, String ex) {
		jc.setExcludes(ex.split(","));
		return JSONObject.fromObject(o, jc).toString();
	}

	@SuppressWarnings("rawtypes")
	public static String from(Object o, Class ex) {
		return from(o, getExcludes(ex));
	}

	@SuppressWarnings("rawtypes")
	public static String from(Collection o) {
		return JSONArray.fromObject(o).toString();
	}

	@SuppressWarnings("rawtypes")
	public static String from(Collection o, String[] ex) {
		jc.setExcludes(ex);
		return JSONArray.fromObject(o, jc).toString();
	}

	@SuppressWarnings("rawtypes")
	public static String from(Collection o, String ex) {
		jc.setExcludes(ex.split(","));
		return JSONArray.fromObject(o, jc).toString();
	}

	@SuppressWarnings("rawtypes")
	public static String from(Collection o, Class ex) {
		return from(o, getExcludes(ex));
	}

	public static Object fromString(String str) {
		return JSONSerializer.toJava(JSONSerializer.toJSON(str));
	}
}